package com.zr.ssm.controller;

import com.zr.ssm.pojo.Result;
import com.zr.ssm.pojo.User;
import com.zr.ssm.service.UserService;
import lombok.AllArgsConstructor;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/my")
@AllArgsConstructor
@CrossOrigin
public class UserController {

    UserService userService;

    @GetMapping("/userinfo")
    public Result getUserInfo(HttpServletRequest request){
        Result result = new Result(0, "query ok");
        Integer userId = (Integer) request.getAttribute("userId");
        User user = userService.selectByUserId(userId);
        result.setData(user);
        return result;
    }

    @PostMapping("/userinfo")
    public Result updateInfo(User user){
        Result result = new Result(0, "update ok");
        Boolean flag = userService.updateUserInfo(user);
        if (!flag){
            result.setStatus(1);
            result.setMessage("update fail");
        }
        return result;
    }

    @PostMapping("/updatepwd")
    public Result updatePwd(String newPwd, HttpServletRequest request){
        Result result = new Result(0, "update password ok");
        Integer id = (Integer) request.getAttribute("userId");
        Boolean flag = userService.updatePwd(newPwd, id);
        if (!flag){
            result.setStatus(1);
            result.setMessage("update password fail");
        }
        return result;
    }

    @PostMapping("/update/avatar")
    public Result updateAvatar(String avatar, HttpServletRequest request){
        Result result = new Result(0, "update avatar ok");
        Integer id = (Integer) request.getAttribute("userId");
        Boolean flag = userService.updateAvatar(avatar, id);
        if (!flag){
            result.setStatus(1);
            result.setMessage("update avatar fail");
        }
        return result;
    }
}
